<template>
  <a-layout-header style="background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);;
                          padding: 6px;
                          margin: 0;
                          position: fixed; /* 使页头悬浮 */
                          top: 0; /* 位于顶部 */
                          width: 100%; /* 宽度占满屏幕 */
                          z-index: 5; /* 确保在内容之上 */">
    <div style="min-height: 80px; margin-top: 10px">
      <a-flex gap="middle" horizontal justify="center" align="center">
        <div style="width: 25%">
          <router-link to="/">
            <a-image :width="70" :preview="false" :src="logo2"></a-image>
          </router-link>
        </div>
        <div :style="{width: '50%'}">
          <a-input-search
              v-model:value="searchValue"
              placeholder="搜点好康的~~"
              size="large"
              allowClear
              :loading="loading"
              @search="onSearch"
          />
        </div>
        <div :style="{width: '25%'}">
          <div v-if="loginStatus">
            <a-row :gutter="16" justify="space-around" align="middle">
              <a-col class="gutter-row" :span="6">
                <div class="gutter-box">
                  <a-popover placement="bottom">
                    <template #content>
                      <p>Content</p>
                      <a-divider />
                      <a-button @click="handleLogout" size="large" style="width: 200px" type="primary" danger ghost>退出</a-button>
                    </template>
                    <template #title>
                      <span>{{loginSession.nickname}}</span>
                    </template>
                    <a>
                      <a-avatar :src="loginSession.header" shape="square" :size="52" @click="userCenter"/>
                    </a>
                  </a-popover>
                </div>
              </a-col>
              <a-col class="gutter-row" :span="4">
                <div class="gutter-box">
                  <a-flex vertical>
                    <div style="height: 80%">
                      <a-badge count="0" :style="{fontSize: '10px'}">
                        <icon :style="{ fontSize: '32px' }" @click="messageCenter">
                          <template #component>
                            <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" class="bi bi-chat-square-text-fill" viewBox="0 0 16 16">
                              <path style="color: black" d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.5a1 1 0 0 0-.8.4l-1.9 2.533a1 1 0 0 1-1.6 0L5.3 12.4a1 1 0 0 0-.8-.4H2a2 2 0 0 1-2-2V2zm3.5 1a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1h-9zm0 2.5a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1h-9zm0 2.5a.5.5 0 0 0 0 1h5a.5.5 0 0 0 0-1h-5z"/>
                            </svg>
                          </template>
                        </icon>
                      </a-badge>
                    </div>
                    <div style="height: 20%">
                      消息
                    </div>
                  </a-flex>
                </div>
              </a-col>
              <a-col class="gutter-row" :span="4">
                <div class="gutter-box">
                  <a-flex vertical>
                    <div style="height: 80%">
                      <icon :style="{ fontSize: '32px' }" @click="playHistory">
                        <template #component>
                          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" class="bi bi-clock-history" viewBox="0 0 16 16">
                            <path style="color: black" d="M8.515 1.019A7 7 0 0 0 8 1V0a8 8 0 0 1 .589.022l-.074.997zm2.004.45a7.003 7.003 0 0 0-.985-.299l.219-.976c.383.086.76.2 1.126.342l-.36.933zm1.37.71a7.01 7.01 0 0 0-.439-.27l.493-.87a8.025 8.025 0 0 1 .979.654l-.615.789a6.996 6.996 0 0 0-.418-.302zm1.834 1.79a6.99 6.99 0 0 0-.653-.796l.724-.69c.27.285.52.59.747.91l-.818.576zm.744 1.352a7.08 7.08 0 0 0-.214-.468l.893-.45a7.976 7.976 0 0 1 .45 1.088l-.95.313a7.023 7.023 0 0 0-.179-.483zm.53 2.507a6.991 6.991 0 0 0-.1-1.025l.985-.17c.067.386.106.778.116 1.17l-1 .025zm-.131 1.538c.033-.17.06-.339.081-.51l.993.123a7.957 7.957 0 0 1-.23 1.155l-.964-.267c.046-.165.086-.332.12-.501zm-.952 2.379c.184-.29.346-.594.486-.908l.914.405c-.16.36-.345.706-.555 1.038l-.845-.535zm-.964 1.205c.122-.122.239-.248.35-.378l.758.653a8.073 8.073 0 0 1-.401.432l-.707-.707z"/>
                            <path style="color: black" d="M8 1a7 7 0 1 0 4.95 11.95l.707.707A8.001 8.001 0 1 1 8 0v1z"/>
                            <path style="color: black" d="M7.5 3a.5.5 0 0 1 .5.5v5.21l3.248 1.856a.5.5 0 0 1-.496.868l-3.5-2A.5.5 0 0 1 7 9V3.5a.5.5 0 0 1 .5-.5z"/>
                          </svg>
                        </template>
                      </icon>
                    </div>
                    <div style="height: 20%">
                      历史
                    </div>
                  </a-flex>
                </div>
              </a-col>
              <a-col class="gutter-row" :span="4">
                <div class="gutter-box">
                  <a-flex vertical>
                    <div style="height: 80%">
                      <icon :style="{ fontSize: '32px' }" @click="upload">
                        <template #component>
                          <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" class="bi bi-cloud-upload-fill" viewBox="0 0 16 16">
                            <path style="color: black" fill-rule="evenodd" d="M8 0a5.53 5.53 0 0 0-3.594 1.342c-.766.66-1.321 1.52-1.464 2.383C1.266 4.095 0 5.555 0 7.318 0 9.366 1.708 11 3.781 11H7.5V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V11h4.188C14.502 11 16 9.57 16 7.773c0-1.636-1.242-2.969-2.834-3.194C12.923 1.999 10.69 0 8 0zm-.5 14.5V11h1v3.5a.5.5 0 0 1-1 0z"/>
                          </svg>
                        </template>
                      </icon>
                    </div>
                    <div style="height: 20%">
                      投稿
                    </div>
                  </a-flex>
                </div>
              </a-col>
            </a-row>
          </div>
          <div v-if="!loginStatus">
            <a-space align="baseline" :size="10" >
              <router-link to="/login">登录</router-link>
              <router-link to="/register">注册</router-link>
            </a-space>
          </div>
        </div>
      </a-flex>
    </div>
  </a-layout-header>
</template>

<script setup>
import {ref, onBeforeMount, createVNode, onBeforeUnmount} from 'vue';
import {getLoginStatus, getSession, logout} from "@/api/LoginRequest.js";
import Icon, {LogoutOutlined} from "@ant-design/icons-vue";
import router from "@/router";
import {message, Modal} from "ant-design-vue";
import logo2 from "@/assets/svgs/logo2.svg";
import {useSocketStore} from "@/utils/websocket";
import Pubsub from "pubsub-js";

const searchValue = ref('');
const loading = ref(false);
const loginStatus = ref(false);
const loginSession = ref({});
const emit = defineEmits(['get-instance']);

// 搜索完成的信号
let searchDone = Pubsub.subscribe('searchDone', (msg, searchValue) => {
  loading.value = false;
});

/**
 * 综合搜索
 * @param searchValue 搜索值
 */
function onSearch(searchValue){
  if(searchValue.length > 0 && searchValue.length < 33) {
    const url = router.currentRoute.value.fullPath;
    if (url.includes('search')) {
      // 当前在搜索页面
      loading.value = true
      Pubsub.publish('searchBegin', searchValue);
    } else {
      router.push({
        path: '/search/video',
        query: {
          keyword: searchValue,
        },
      });
    }
  } else {
    message.info('搜索内容不能为空且长度不能超过32个字符');
  }
}

function userCenter() {
  const targetRoute = router.resolve({
    name: 'userCenter',
    params: {
      userId: loginSession.value.userId
    }
  });
  window.open(targetRoute.href, '_blank');
}

function messageCenter(){
  router.push('/message-center/own');
}

function collect(){
  console.log('收藏');
}

function playHistory(){
  console.log('播放历史');
}

function upload(){
  router.push("/upload-manager/upload-opinion")
}

function handleLogout() {
  Modal.confirm({
    title: '退出?',
    icon: createVNode(LogoutOutlined),
    content: '退出了就不能康好康的咯~',
    onOk() {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          if(res.code === 0) {
            Pubsub.publish('login-sign', 'out');
            localStorage.removeItem('token');
            loginStatus.value = false;
            loginSession.value = {};
            if(typeof useSocketStore().ws !== "undefined"){
              useSocketStore().closeWs();
            }

            const redirectPath = localStorage.getItem("redirectPath");
            if (typeof redirectPath !== "undefined" && redirectPath !== '') {
              router.push(redirectPath);
            } else {
              router.push('/');
            }
            resolve();
          } else {
            reject(res.msg)
          }
        })
      }).catch(() => console.log('Oops errors!'));
    },
    onCancel() {},
  });
}

onBeforeMount(_=> {
  if(router.currentRoute.value.fullPath.includes('search') &&
      router.currentRoute.value.query.keyword !== undefined
  ) {
    loading.value = true;
    searchValue.value = router.currentRoute.value.query.keyword;
  }

  getSession().then(res => {
    if(res.code === 0){
      loginStatus.value = true;
      loginSession.value = res.data.dataMap.userSession;
      emit('get-instance', {session: loginSession.value});
      Pubsub.publish('user-session', loginSession.value);
    }else if(res.code === 20002){
      // 未登录
      loginStatus.value = false;
    } else {
      loginStatus.value = false;
      message.error('获取用户session失败-'+res.msg);
    }
  })
})

onBeforeUnmount(_ => {
  Pubsub.unsubscribe(searchDone);
})
</script>

<style>

</style>